package cn.ac.big.bigd.transfer;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class BigFileCopy {
	public static boolean  isexitsPath(String path)throws InterruptedException{
		String [] paths=path.split("/");
		StringBuffer fullPath=new StringBuffer();
		for (int i = 0; i < paths.length; i++) {
			fullPath.append(paths[i]).append("/");
			File file=new File(fullPath.toString());
			if(paths.length-1!=i){//判断path到文件名时，无须继续创建文件夹！
				if(!file.exists()){
					file.mkdir();
					System.out.println("创建目录为："+fullPath.toString());
					Thread.sleep(1500);
				}
			}
		}
		File file=new File(fullPath.toString());//目录全路径
		if (!file.exists()) {
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * @param source
	 * @param dest
	 * @throws IOException
	 */
	public static int copyByChannelToChannel(String source, String dest) throws Exception {
		File source_tmp_file = new File(source);
		if (!source_tmp_file.exists()) {
			return -1;
		}
		RandomAccessFile source_file = new RandomAccessFile(source_tmp_file, "r");
		FileChannel source_channel = source_file.getChannel();
		File dest_tmp_file = new File(dest);
		if(isexitsPath(dest)){



			if (!dest_tmp_file.isFile()) {
				if (!dest_tmp_file.createNewFile()) {
					source_channel.close();
					source_file.close();
					return -1;
				}
			}else{
				dest_tmp_file.delete();
			}
		}
		RandomAccessFile dest_file = new RandomAccessFile(dest_tmp_file, "rw");
		FileChannel dest_channel = dest_file.getChannel();
		long left_size = source_channel.size();
		long position = 0;
		while (left_size > 0) {
			long write_size = source_channel.transferTo(position, left_size, dest_channel);
			position += write_size;
			left_size -= write_size;
		}
		source_channel.close();
		source_file.close();
		dest_channel.close();
		dest_file.close();
		return 1;
	}
	
	
	public static void main(String[] args) {
		try {
			long start_time = System.currentTimeMillis();
			BigFileCopy.copyByChannelToChannel("D:/GWH/WGS000001/Filter5M.fasta", "D:/GWH2/WGS000001/testcopy.fastq");
			long end_time = System.currentTimeMillis();
			System.out.println("copy time = " + (end_time - start_time));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
